package com.zjuee.core.translation.handledata.impl;

import com.zjuee.core.translation.handledata.DataHandlerStrategy;
import com.zjuee.core.translation.utils.CaseUtil;
import com.zjuee.core.translation.utils.MergeMapOrListUtil;
import com.zjuee.core.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wu liang
 * @since 2020/10/10 14:30
 */
@Slf4j
public abstract class AbstractDataHandler implements DataHandlerStrategy {

    @Resource
    private RedisUtil redisUtil;



    @Override
    public Object handleListData(Object obj, String... str) {
        Map<Object,Object> map = new HashMap<>();
        Object resultObj = new Object();
//        //根据数组，redis查询配置数据
        for (String s : str) {
            //查询数据
            Map<Object,Object> resultMap = redisUtil.hmget(s);
            //整合数据
            MergeMapOrListUtil.mergeMapPlus(map, resultMap, s);
        }
        //log.info(map.toString());
        //todo 后续优化（数据没有 - 可调用存放缓存的接口，先把数据存放redis，在查询redis）  如果数据为空  - 则查询数据库

        if(obj instanceof List){
            List<Object> resultList = new ArrayList<>();
            List<Object> list = CaseUtil.castList(obj, Object.class);
            for (int i = 0; i < list.size(); i++){
                //钩子方法 - 子类实现
                Object data =  getData(list.get(i), map, str);
                resultList.add(data);
            }
            resultObj =  (Object) resultList;
        }else {
            //钩子方法 - 子类实现
            resultObj =  getData(obj, map, str);
        }

        return resultObj;
    }


    public abstract <T> T getData(T data, Map<Object,Object> map, String... str);


    public String getStr(Map<Object, Object> map, String clu, String[] str, Integer index){
        String[] strings = clu.toString().split(",");
        String result = null;
        for (String s : strings) {
            if (result != null) {
                result = result + "," + map.get(s + str[index] == null ? "" : s + str[index]);
            } else {
                result = map.get(s + str[index] == null ? "" : s + str[index]).toString();
            }
        }
        if(",".equals(result)){
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }
}
